package monster.com.cvh.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import monster.com.cvh.R;
import monster.com.cvh.activity.base.PermissionActivity;
import monster.com.cvh.bean.MessageEvent;
import monster.com.cvh.bean.PushBean;
import monster.com.cvh.bean.ResultBean;
import monster.com.cvh.constant.Constans;
import monster.com.cvh.database.GreenDAOManager;
import monster.com.cvh.database.ResumeInfoBean;
import monster.com.cvh.event.RefreshResumePreviewEvent;
import monster.com.cvh.event.VisitorRefreshEvent;
import monster.com.cvh.fragment.HomeFragment;
import monster.com.cvh.fragment.MyFragment;
import monster.com.cvh.fragment.ResumeFragment;
import monster.com.cvh.gen.ResumeInfoBeanDao;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 主页界面
 */

public class MainActivity extends PermissionActivity {
    private static final String TAG = "MainActivity";
    @BindView(R.id.iv_main_bottom_home)
    ImageView mIvBottomHome;
    @BindView(R.id.tv_main_bottom_home)
    TextView mTvBottomHome;
    @BindView(R.id.ll_main_botttom_home)
    LinearLayout mLlBottomHome;
    @BindView(R.id.iv_main_bottom_resume)
    ImageView mIvBottomResume;
    @BindView(R.id.tv_main_bottom_resume)
    TextView mTvBottomResume;
    @BindView(R.id.ll_main_botttom_resume)
    LinearLayout mLlBottomResume;
    @BindView(R.id.iv_main_bottom_user)
    ImageView mIvBottomUser;
    @BindView(R.id.tv_main_bottom_user)
    TextView mTvBottomUser;
    @BindView(R.id.ll_main_botttom_user)
    LinearLayout mLlBottomUser;
    private Fragment mResumeFragment;
    private Fragment mUserFragment;
    private Fragment mHomeFragment;


    @Override
    protected int getContentViewResId() {
        changeStatusBarColorDark(this, R.color.white);
        return R.layout.activity_main;
    }

    @Override
    protected void initEvent() {
        setSelect(1);
        //注册EventBus
        EventBus.getDefault().register(this);
    }

    /**
     * 接收事件
     *
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
        Log.i(TAG, "Event: " + messageEvent.getMessage());
        switch (messageEvent.getMessage()) {
            case "finshMain":
                finish();
                break;

        }
    }

    @Override
    protected void initData() {
        //检查token是否为空，为空就不上传push_id
        if (!SPUtils.getString(MainActivity.this, "token", "").equals("")) {
            //传push_id 给后台
            OkGo.<String>put(MyConstant.MODIFY_PUSH_ID).params("token", SPUtils.getString(MainActivity.this, "token", ""))
                    .params("push_id", SPUtils.getString(MainActivity.this, "pushId", ""))
                    .params("os_type", "android").execute(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    Gson gson = new Gson();
                    PushBean pushBean = gson.fromJson(s, PushBean.class);
                    if (!String.valueOf(pushBean.getCode()).equals("")) {
                        switch (pushBean.getCode()) {
                            case 1:
                                Log.i("lixiaofei", "onSuccess: " + pushBean.getData().getPush_id());
                                break;
                            case -1002:
                                Log.i("lixiaofei", "onSuccess: " + pushBean.getMsg());
                                break;
                            case -1003:
                                Log.i("lixiaofei", "onSuccess: " + pushBean.getMsg());
                                break;
                            case -1004:
                                Log.i("lixiaofei", "onSuccess: " + pushBean.getMsg());
                                break;
                            case -154:
                                Log.i("lixiaofei", "onSuccess: " + pushBean.getMsg());
                                break;
                            case -155:
                                Log.i("lixiaofei", "onSuccess: " + pushBean.getMsg());
                                break;

                        }
                    }
                }
            });

        } else {
            Log.i("lixiaofei", "initData: " + "我是游客");
        }
        checkUnlock();
    }

    /**
     * 检查模板解锁情况
     */
    private void checkUnlock() {
        if (isLogined()) {
            OkGo.<String>post(MyConstant.UNLOCK_RESUME_TEMPLATE)
                    .tag(this)
                    .params(MyConstant.TOKEN, SPUtils.getString(this, MyConstant.TOKEN, ""))
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            Log.e(TAG, "解锁模板: " + s);
                            try {
                                ResultBean bean = new Gson().fromJson(s, ResultBean.class);
                                if (bean != null) {
                                    boolean isLock = bean.getCode() == 1 ? false : true;
                                    ResumeInfoBeanDao dao = GreenDAOManager.getInstance().getmDaoSession().getResumeInfoBeanDao();
                                    List<ResumeInfoBean> list = dao.queryBuilder().list();
                                    for (ResumeInfoBean resumeInfoBean : list) {
                                        //此处setIsLock表示有没有锁，true有false没
                                        resumeInfoBean.setIsLock(isLock);
                                        dao.update(resumeInfoBean);
                                    }
                                    //设置解锁标记，true解锁，false没解锁
                                    SPUtils.putBoolean(MainActivity.this, Constans.SP_UNLOCK_RESUME, !isLock);
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    });
        }
    }


    @OnClick({R.id.ll_main_botttom_home, R.id.ll_main_botttom_resume, R.id.ll_main_botttom_user})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_main_botttom_home:
                setSelect(0);
                break;
            case R.id.ll_main_botttom_resume:
                setSelect(1);
                break;
            case R.id.ll_main_botttom_user:
                setSelect(2);
                break;
        }
    }

    /**
     * 切换fragment
     */
    private void setSelect(int fragmentId) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideFragment(transaction);
        switch (fragmentId) {
            case 0:
                if (mHomeFragment == null) {
                    mHomeFragment = new HomeFragment();
                    transaction.add(R.id.id_content, mHomeFragment);
                } else {
                    transaction.show(mHomeFragment);
                }
                mIvBottomHome.setImageResource(R.mipmap.tab_home_blue);
                mIvBottomResume.setImageResource(R.mipmap.tab_resume_black);
                mIvBottomUser.setImageResource(R.mipmap.tab_mine_black);

                mTvBottomHome.setTextColor(Color.rgb(62, 200, 209));
                mTvBottomResume.setTextColor(Color.parseColor("#888888"));
                mTvBottomUser.setTextColor(Color.parseColor("#888888"));
                changeStatusBarColorDark(MainActivity.this, R.color.white);
                break;
            case 1:
                if (mResumeFragment == null) {
                    mResumeFragment = new ResumeFragment();
                    transaction.add(R.id.id_content, mResumeFragment);
                } else {
                    transaction.show(mResumeFragment);
                }
                mIvBottomResume.setImageResource(R.mipmap.tab_resume_blue);
                mIvBottomUser.setImageResource(R.mipmap.tab_mine_black);
                mIvBottomHome.setImageResource(R.mipmap.tab_home_black);
                mTvBottomResume.setTextColor(Color.rgb(62, 200, 209));

                mTvBottomUser.setTextColor(Color.parseColor("#888888"));
                mTvBottomHome.setTextColor(Color.parseColor("#888888"));
                changeStatusBarColorDark(MainActivity.this, R.color.white);
                break;
            case 2:
                if (mUserFragment == null) {
                    mUserFragment = new MyFragment();
                    transaction.add(R.id.id_content, mUserFragment);
                } else {
                    transaction.show(mUserFragment);
                }
                mIvBottomUser.setImageResource(R.mipmap.tab_mine_blue);
                mTvBottomUser.setTextColor(Color.rgb(62, 200, 209));

                mIvBottomResume.setImageResource(R.mipmap.tab_resume_black);
                mIvBottomHome.setImageResource(R.mipmap.tab_home_black);

                mTvBottomHome.setTextColor(Color.parseColor("#888888"));
                mTvBottomResume.setTextColor(Color.parseColor("#888888"));
                changeStatusBarColorDark(MainActivity.this, R.color.colorPrimary);
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 隐藏fragment
     */
    private void hideFragment(FragmentTransaction transaction) {
        if (mResumeFragment != null) {
            transaction.hide(mResumeFragment);
        }
        if (mUserFragment != null) {
            transaction.hide(mUserFragment);
        }
        if (mHomeFragment != null) {
            transaction.hide(mHomeFragment);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //回到桌面
            new AlertDialog.Builder(MainActivity.this).setTitle("温馨提醒").setMessage("确定要退出应用吗？").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            }).show();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //刷新新模板
        boolean isRefreshResume = intent.getBooleanExtra(Constans.PHOTOACTIVITY_REFRESH_RESUME, true);
        if (isRefreshResume) {
            RefreshResumePreviewEvent.getInstance().onRefreshResumePreview();
        }
        VisitorRefreshEvent.getInstance().onVisitorLogin();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constans.LOGIN_WITHOUT_OPTION || requestCode == Constans.LOGIN_WITHOUT_OPTION) {
            VisitorRefreshEvent.getInstance().onVisitorLogin();
        }
    }
}